const User = require('../../model/User')
const bcrypt = require('bcrypt')
const stringRandom = require('string-random');
var auth_code_obj = require('../email/sendemail')
module.exports = async (req, res, next) => {
    var auth_code = auth_code_obj.verification || []
    const { username, email, password, VerificationCode } = req.body
    if (!email) {
        res.sendResult(null, 400, '请输入邮箱！')
        return
    }
    if (!VerificationCode) {
        res.sendResult(null, 400, '请输入验证码！')
        return
    }
    if (auth_code.length == 0) {
        res.sendResult(null, 400, '你好像没有发送验证码偶！')
        return
    }
    for (var i = 0; i < auth_code.length; i++) {
        if (auth_code[i].email == email) {
            if (auth_code[i].Verification != VerificationCode) {
                res.sendResult(null, 400, '验证码错误')
                return
            }
        }
    }
    if (!username) {
        res.sendResult(null, 400, '请输入用户名！')
        return
    }
    if (!password) {
        res.sendResult(null, 400, '请输入密码！')
        return
    }
    // 根据邮箱查询用户 
    const model = await User.findOne({ where: { email } })
    if (model) {
        res.sendResult(null, 400, '邮箱已存在！')
        return
    }
    const isusername = await User.findOne({ where: { username } })
    if (isusername) {
        res.sendResult(null, 400, '用户名已经存在！')
        return
    }
    const regEmail = /^[^\u4e00-\u9fa5]+$/;
    if (!regEmail.test(username)) {
        res.sendResult(null, 400, '用户名不能有中文')
        return
    }
    // 生成随机字符串
    let salt = await bcrypt.genSalt(10)
    // 进行加密
    let pass = await bcrypt.hash(password, salt)
    // 生存随机字符
    let key = stringRandom(32)
    // 创建用户
    const createUser = await User.create({ username, email, password: pass, key })
    // 创建失败
    if (!createUser) {
        res.sendResult(null, 422, '创建失败')
        return
    }
    // 创建成功
    res.sendResult(null, 201, '注册成功！')
}





